<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有!                                 |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: Xmh<xiangminghu@clcw.com.cn>                                   |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\Agent;

use AuctionCore\ClcwUser\ClcwUser;

class Agent
{
    private $aid = null;

    public function __construct($aid)
    {
        $this->aid = $aid;
    }

    //经纪人列表
    public static function getAgentList($page, $page_size, $params)
    {
        $page = $page < 1 ? 1 : (int)$page;
        $page_size = $page_size < 1 ? 10 : (int)$page_size;
        $map = [];
        $clcwUser = new ClcwUser();
        /**
         * 搜索条件：1、个人ID 2、帐号 3、邀请人帐号 4、类型：顶级、非顶级 5、状态：启用、禁用 6、开始时间 7、结束时间
         */
        if ($params['u_id']) {
            $map['ag.uid'] = ['LIKE', '%' . $params['u_id'] . '%'];
        }
        if ($params['agent']) {
            $user = $clcwUser->getUserInfoByMobile(trim($params['agent']));
            $map['ag.uid'] = ['eq', $user['user_id']];
        }
        if ($params['superior']) {
            $superior = trim($params['superior']);
            $user = $clcwUser->getUserInfoByMobile($superior);
            if (!empty($user)) {
                $agent_info = Agent::get_detail_by_uid($user['user_id']);
                if (!empty($agent_info)) {
                    $map['ag.superior_id'] = ['eq', $agent_info['aid']];
                }
            }
        }
        if ($params['agent_type']) {
            $agentType = $params['agent_type'];
            if ($agentType == 1) {
                $map['ag.superior_id'] = ['eq', 0];
            } elseif ($agentType == 2) {
                $map['ag.superior_id'] = ['gt', 0];
            }
        }
        if ($params['agent_status']) {
            $agentStatus = $params['agent_status'];
            if ($agentStatus == 1) {
                $map['u.status'] = ['eq', 1];
            } elseif ($agentStatus == 2) {
                $map['u.status'] = ['eq', 2];
            }
        }
        if ($params['start_time']) {
            $map['ag.create_time'] = ['egt', strtotime($params['start_time'] . ' 00:00:00')];
        }
        if ($params['end_time']) {
            $map['ag.create_time'] = ['elt', strtotime($params['end_time'] . ' 23:59:59')];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['ag.create_time'] = [['egt', strtotime($params['start_time'] . ' 00:00:00')], ['elt', strtotime($params['end_time'] . ' 23:59:59')]];
        }
        $cols = 'ag.*,u.mobile,u.nick_name,u.icard';
        $order = "ag.aid DESC";
        $total = M('agent', 'clcw_', 'DB_CLCW')->alias('ag')->where($map)
            ->join("clcw_user AS u ON u.user_id = ag.uid")
            ->count();
        $list = M('agent', 'clcw_', 'DB_CLCW')->alias('ag')->field($cols)->where($map)->order($order)
            ->join("clcw_user AS u ON u.user_id = ag.uid")
            ->page($page)
            ->limit($page_size)
            ->select();
//        dump($list);
        if (!empty($list)) {
            $clcwUser = new ClcwUser();
            foreach ($list as $k => $v) {
                if (!empty($v['superior_id'])) {
                    $uid = self::getDetailByAid($v['superior_id']);
                    $info = $clcwUser->getClcwUserInfo($uid['uid']);
                    $list[$k]['invite_people'] = $info['mobile'];
                    $list[$k]['agent_type'] = 2; //非顶级
                } else {
                    $list[$k]['agent_type'] = 1; //顶级
                }
                $directAgentResult = self::getDirectAgentNum($v['aid']);
                $list[$k]['direct_agent_num'] = $directAgentResult['total'];
                $list[$k]['indirect_agent_num'] = self::getIndirectAgentNum($directAgentResult['agent_list']);
                $list[$k]['my_customer_num'] = self::getMyCustomerNum($v['uid']);
                $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }
        }
        $result = [
            'list'  => $list,
            'total' => $total,
        ];
        return $result;
    }


    /**
     * 计算直接经纪人数量
     *
     * @param int $agentId
     */
    private static function getDirectAgentNum($agentId)
    {
        $condition['superior_id'] = $agentId;
        $agentList = M('agent', 'clcw_', 'DB_CLCW')->where($condition)->select();
        $result = [
            'agent_list' => $agentList,
            'total'      => count($agentList)
        ];
        return $result;
    }

    /**
     * 计算间接经纪人数量
     *
     * @param array $agentList
     */
    private static function getIndirectAgentNum($agentList = [])
    {
        $num = 0;
        if (!empty($agentList)) {
            foreach ($agentList as $bl) {
                $map['superior_id'] = $bl['aid'];
                $indirect_agent_list = M('agent', 'clcw_', 'DB_CLCW')->where($map)->select();
                $indirect_num = 0;
                if (empty($indirect_agent_list)) {
                    continue;
                }
                $indirect_num = count($indirect_agent_list);
                $indirect_num = $indirect_num + self::getIndirectAgentNum($indirect_agent_list);
                $num = $num + $indirect_num;
            }
        }
        return $num;
    }

    /**
     * 计算我的客户数量
     *
     * @param int $uid
     */
    private static function getMyCustomerNum($uid)
    {
        $condition['uid'] = $uid;
        $total = M('my_customer', 'clcw_', 'DB_CLCW')->where($condition)->count();
        return $total;
    }

    /**
     * 添加经纪人
     *
     * @param integer $uid
     * @param int     $mobile
     * @param integer $superior_id
     *
     * @return mixed
     */
    public static function create($uid, $mobile, $superior_id = 0)
    {
        if ($uid < 1) {
            return false;
        }
        $data = [
            'uid'         => $uid,
            'superior_id' => $superior_id,
            'invite_code' => $mobile,
            'create_time' => time()
        ];
        M('', 'clcw_', 'DB_CLCW')->startTrans();
        $aid = M('agent', 'clcw_', 'DB_CLCW')->add($data);
        if ($aid < 1) {
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
        M('', 'clcw_', 'DB_CLCW')->commit();
        return $aid;
    }

    /**
     * 通过aid获取经纪人信息
     *
     * @param $aid
     *
     * @return bool|mixed
     */
    public static function getDetailByAid($aid)
    {
        if (intval($aid) < 1) {
            return false;
        }
        return M('agent', 'clcw_', 'DB_CLCW')->where(['aid' => $aid])->find();
    }

    //根据uid获取经纪人信息
    public static function get_detail_by_uid($uid)
    {
        if (intval($uid) < 1) {
            return false;
        }
        return M('agent', 'clcw_', 'DB_CLCW')->where(['uid' => $uid])->find();
    }
}